package response

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"go-zero-demo/common/xerr"
	"google.golang.org/grpc/status"
	"net/http"
)

type R struct {
	Code uint32 `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data,omitempty"`
}

type NullJson struct{}

func Success(data any) *R {
	return &R{200, "OK", data}
}

type ErrR struct {
	Code uint32 `json:"code"`
	Msg  string `json:"msg"`
}

func Error(code uint32, msg string) *ErrR {
	return &ErrR{code, msg}
}

func ApiResult(r *http.Request, w http.ResponseWriter, resp any, err error) {
	if err == nil {
		r := Success(resp)
		httpx.WriteJson(w, http.StatusOK, r)
	} else {
		errCode := xerr.SERVER_ERROR
		errMsg := xerr.GetErrMsg(errCode)

		causeErr := errors.Cause(err)
		fmt.Printf("value: %v type: %T\n", causeErr, causeErr)
		if e, ok := causeErr.(*xerr.BisErr); ok {
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		} else {
			if grpcErr, ok := status.FromError(causeErr); ok {
				grpcCode := uint32(grpcErr.Code())
				if xerr.IsBisCodeErr(grpcCode) {
					errCode = grpcCode
					errMsg = grpcErr.Message()
				}
			}
		}

		logx.WithContext(r.Context()).Errorf("【API接口错误】 : %+v ", err)
		httpx.WriteJson(w, http.StatusBadRequest, Error(errCode, errMsg))
	}
}

// ParamErrorResult http 参数校验错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s ,%s", xerr.GetErrMsg(xerr.REQUEST_PARAM_ERROR), err.Error())
	httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.REQUEST_PARAM_ERROR, errMsg))
}
